<?
require('../bootstrap.php');
require_once('includes/page_index_handling.php');
auth_redirect();

if (isset($_POST['method'])) {
	$method = $_POST['method'];
	switch ($method) {
		case 'tooglePageView': {
			$return_value = '';
			$id = escape($_POST['page_id']);			
			$res = $db->get_result("SELECT id, viewed FROM $pages_table WHERE id = $id");
			$viewed = $res[0]['viewed'];
			if (isset($viewed)) {
				$viewed = ($viewed == 1) ? 0 : 1;
				if ($db->execute("UPDATE $pages_table SET `viewed` = $viewed WHERE id = $id")) {
					$return_value = 'SUCCESS';
				} else {
					$return_value = 'FAILURE';
				}				
			} 
			if ($return_value != 'SUCCESS') {
				echo 'FAILURE';
			} else {
				echo $return_value;
			}
			break;
		}
		case 'movePage': {	
			$return = '';
			$post = escape_array($_POST);
			if (is_numeric($post['page_id']) && ($post['direction'] == 'UP' || $post['direction'] == 'DOWN')) {
				
				$id = $post['page_id'];
				$dir = $post['direction'];
				if ($dir == 'UP') {
					page_moveUp($id);
				} else if ($dir == 'DOWN') {
					page_moveDown($id);
				}
				
				$return = 'SUCCESS';
			}
			if ($return != '') {
				echo $return;
			} else {
				echo 'FAILURE';
			}
			break;
		}
		case 'retrievePages': {
			$pages = $db->get_result("SELECT id,title,viewed,`index` FROM $pages_table ORDER BY `index`");
			echo json_encode($pages);
			break;
		}
	}
}

?>